package cn.oi.klittle.era.dialog.version

import android.content.Context
import android.graphics.Color
import android.os.Build
import android.view.Gravity
import android.view.View
import android.view.View.OVER_SCROLL_NEVER
import android.widget.ScrollView
import android.widget.TextView
import cn.oi.klittle.era.R
import cn.oi.klittle.era.base.KBaseDialog
import cn.oi.klittle.era.base.KBaseUi
import cn.oi.klittle.era.comm.kpx
import cn.oi.klittle.era.dialog.timi.KTimiAlertDialog
import cn.oi.klittle.era.exception.KCatchException
import cn.oi.klittle.era.utils.KLoggerUtils
import cn.oi.klittle.era.widget.compat.KTextView
import org.jetbrains.anko.*
import java.lang.Exception

//fixme 版本更新,界面升级版。点击下载之后的更新进度在：KVersionLevelProgressbarDialog里。
//fixme 更新文本超过界面了，可以上下滑动。

//                    var version: KVersionLevelDialog? = null
//                    var mession = getString(R.string.kversion_update_mession)//有版本更新,是否更新版本?
//                    onClick {
//                        if (version == null) {
//                            version = KVersionLevelDialog(ctx)
//                        }
//                        version?.url = "http://test.bwg2017.com/UploadFile/AppVersion/202010201055245616.apk"//下载apk地址
//                        version?.srcFileName = null//下载文件名，为空会自动获取网络名称。
//                        version?.isForceLoad = false//是否强制下载。true强制下载会隐藏取消按钮，和屏蔽返回键。
//                        title(getString(R.string.kfaxianapp))//标题
//                        version?.mession(mession)//fixme 显示更新文本内容
//                        //显示更新版本和内容;fixme mession 和 setVersionNameAndContent 都是显示更新的内容。
//                        //setVersionNameAndContent(it?.Data?.versionName,it?.Data?.updateLog)
//                        //取消按钮
//                        //negative {}
//                        //确定按钮
//                        positive (getString(R.string.kxiazai)){}
//                        version?.show()
//                    }

open class KVersionLevelDialog(var act: Context, isStatus: Boolean = true, isTransparent: Boolean = false) :
        KBaseDialog(act, isStatus = isStatus, isTransparent = isTransparent) {

    //apk下载链接
    var url: String? = null

    //文件名，包括后缀。如果为null或""空，会自动获取网络上的名称。
    var srcFileName: String? = null

    //文件下载目录，可以为空。如果为空。会使用默认下载目录 KFileLoadUtils里的cacheDir
    var downDir: String? = null

    var isForceLoad = false//fixme 是否强制下载


    override fun onCreateView(context: Context): View? {
        return context.UI {
            ui {
                //fixme 放在scrollView，文本框高度自适应。亲测，高度能随文本的变化而变化。能大能小。
                scrollView {
                    setOverScrollMode(OVER_SCROLL_NEVER);//设置滑动到边缘时无效果模式
                    setVerticalScrollBarEnabled(false);//滚动条隐藏
                    isFillViewport = true
                    verticalLayout {
                        gravity = Gravity.CENTER
                        kverticalLayout {
                            if (Build.VERSION.SDK_INT >= 21) {
                                z = kpx.x(24f)//会有投影，阴影效果。
                            }
                            shadow_radius = kpx.x(12f)
                            shadow {
                                bg_color = Color.WHITE
                                all_radius(kpx.x(0))
                                shadow_color = Color.parseColor("#333333")//效果比Color.BLACK好。
                            }
                            gravity = Gravity.CENTER_VERTICAL
                            leftPadding = kpx.x(32 + 10)
                            rightPadding = leftPadding
                            topPadding = leftPadding
                            bottomPadding = topPadding

                            //标题
                            KTextView(this).apply {
                                id = kpx.id("crown_txt_title")
                                textColor = Color.parseColor("#242424")
                                textSize = kpx.textSizeX(33)
                                gravity = Gravity.CENTER_VERTICAL
                                padding = 0
                                setLineSpacing(kpx.textSizeX(20f), 1f)
                                text = getString(R.string.kversion_update_title)//软件更新
                            }.lparams {
                                width = wrapContent
                                height = wrapContent
                            }

                            //内容
                            KTextView(this).apply {
                                id = kpx.id("crown_txt_mession")
                                textColor = Color.parseColor("#242424")
                                textSize = kpx.textSizeX(32)
                                gravity = Gravity.CENTER_VERTICAL
                                padding = 0
                                setLineSpacing(kpx.textSizeX(20f), 1f)
                                text = getString(R.string.kversion_update_mession)//有版本更新,是否更新版本?
                            }.lparams {
                                width = wrapContent
                                height = wrapContent
                                topMargin = kpx.x(40)
                                bottomMargin = topMargin
                            }
                            linearLayout {
                                gravity = Gravity.CENTER_VERTICAL or Gravity.RIGHT
                                //取消
                                textView {
                                    id = kpx.id("crown_txt_Negative")
                                    //textColor = Color.parseColor("#239F93")
                                    textColor = Color.parseColor("#C8C5C9")
                                    textSize = kpx.textSizeX(32)
                                    leftPadding = kpx.x(32)
                                    rightPadding = leftPadding
                                    text = getString(R.string.kversion_update_no)//暂不更新
                                }.lparams {
                                    width = wrapContent
                                    height = wrapContent
                                }

                                //确定
                                textView {
                                    id = kpx.id("crown_txt_Positive")
                                    //textColor = Color.parseColor("#239F93")
                                    textColor = Color.parseColor("#42A8E1")
                                    textSize = kpx.textSizeX(32)
                                    leftPadding = kpx.x(32)
                                    rightPadding = leftPadding
                                    text = getString(R.string.kversion_update)//更新
                                }.lparams {
                                    width = wrapContent
                                    height = wrapContent
                                }

                            }.lparams {
                                width = matchParent
                                height = wrapContent
                            }
                        }.lparams {
                            width = kpx.x(700)
                            height = wrapContent
                        }
                    }.lparams {
                        width = matchParent
                        height = matchParent
                    }
                }
            }
        }.view
    }

    //标题栏文本
    var txt_title: String? = KBaseUi.getString(R.string.kversion_update_title)//软件更新
    val title: TextView? by lazy { findViewById<TextView>(kpx.id("crown_txt_title")) }
    open fun title(title: String? = getString(R.string.ktishi)): KVersionLevelDialog {
        txt_title = title
        return this
    }

    //信息文本
    var txt_mession: String? = KBaseUi.getString(R.string.kversion_update_mession)//有版本更新,是否更新版本?
    val mession: KTextView? by lazy { findViewById<KTextView>(kpx.id("crown_txt_mession")) }
    open fun mession(mession: String? = null): KVersionLevelDialog {
        txt_mession = mession
        return this
    }

    /**
     * fixme 显示更新版本名称和内容
     * @param versionName 更新版本名称
     * @param versionContent 更新内容
     */
    open fun setVersionNameAndContent(versionName: String?, versionContent: String?) {
        var mession: String? = null
        versionName?.let {
            //更新版本名称
            mession =
                    getString(R.string.kupdate_new) + it + ";" + getString(
                            R.string.kupdate_is
                    )
        }
        //更新内容
        versionContent?.trim()?.let {
            if (it.length > 0) {
                if (mession != null) {
                    mession += "\n"
                }
                mession =
                        mession + getString(R.string.kupdate_content) + it
            }
        }
        //fixme 发现新版本：versionName；是否更新?\n更新内容：versionContent
        mession?.trim()?.let {
            if (it.length > 0) {
                this.mession(it)
            }
        }
    }


    val negative: TextView? by lazy { findViewById<TextView>(kpx.id("crown_txt_Negative")) }

    //左边，取消按钮
    open fun negative(negative: String? = getString(R.string.kcancel), callback: (() -> Unit)? = null): KVersionLevelDialog {
        this.negative?.setText(negative)
        this.negative?.setOnClickListener {
            callback?.run {
                this()//取消回调
            }
            dismiss()//自动关闭
        }
        return this
    }

    val positive: TextView? by lazy { findViewById<TextView>(kpx.id("crown_txt_Positive")) }

    //右边，确定按钮
    open fun positive(postive: String? = getString(R.string.kconfirm), callback: (() -> Unit)? = null): KVersionLevelDialog {
        this.positive?.setText(postive)
        this.positive?.setOnClickListener {
            callback?.run {
                this()//确认回调
            }
            dismiss()//自动关闭
            loadDown()//下载
        }
        return this
    }

    var kVersionLevelProgressbarDialog: KVersionLevelProgressbarDialog? = null//下载今天弹窗，在这里下载。

    //下载
    fun loadDown() {
        if (url != null) {
            if (kVersionLevelProgressbarDialog == null) {
                kVersionLevelProgressbarDialog = KVersionLevelProgressbarDialog(act)
            }
            kVersionLevelProgressbarDialog?.url = url//下载链接
            kVersionLevelProgressbarDialog?.srcFileName = srcFileName//文件名
            kVersionLevelProgressbarDialog?.downDir = downDir//下载目录
            kVersionLevelProgressbarDialog?.show()
        }
    }

    init {
        try {
            //取消
            negative?.setOnClickListener {
                dismiss()//关闭当前弹窗。
            }
            //确定(更新下载)
            positive?.setOnClickListener {
                dismiss()//关闭当前弹窗。
                loadDown();//下载
            }
            isDismiss(false)//默认不消失
            //isLocked(true)//fixme 屏蔽返回键(关闭只能点确定按钮)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    override fun onShow() {
        super.onShow()
        ctx?.runOnUiThread {
            try {
                title?.setText(txt_title)//标题
                mession?.setAutoSplitText(txt_mession)//内容
                if (isForceLoad) {
                    //强制下载
                    negative?.visibility = View.INVISIBLE//隐藏取消按钮
                    isLocked(true)//屏蔽返回键
                } else {
                    //不强制下载
                    negative?.visibility = View.VISIBLE
                    isLocked(false)//不屏蔽返回键
                }
            } catch (e: Exception) {
                KLoggerUtils.e("KVersionLevelDialog显示异常：\t" + KCatchException.getExceptionMsg(e), true)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        mession?.onDestroy()
        kVersionLevelProgressbarDialog?.dismiss()
        kVersionLevelProgressbarDialog?.onDestroy()
    }

}